package com.aididi;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Mono;

@SpringBootApplication
@RestController
public class GatewayFirstSightApplication {

	public static void main(String[] args) {
		SpringApplication.run(GatewayFirstSightApplication.class, args);
	}

	@Bean
	public RouteLocator myRoutes(RouteLocatorBuilder builder){
		String httpUri = "http://httpbin.org:80";
		return builder.routes()
				.route(p ->
						//请求路劲
						p.path("/get").
						//添加filter过滤器，将请求添加一个header,key为username，value为xzx1994。
						filters(f -> f.addRequestHeader("username","xzx1994"))
						//将get请求转发到此地址
						.uri(httpUri))
				.route(p ->
						//断言请求是否进入该路由
						p.host("*.hystrix.com")
						.filters(f ->
						//添加一个hyxtrix的filter
						f.hystrix(config ->
							config.setName("mycmd")
							//hystrix的filter会重定向到fallback方法
							.setFallbackUri("forward:/fallback")))
					.uri(httpUri))
				.build();
	}

	/**
	 * 重定向方法
	 * 输入 curl --dump-header - --header 'Host: www.hystrix.com' http://localhost:8080/delay/3
	 *  将返回fallback
	 * @return
	 */
	@GetMapping("/fallback")
	public Mono<String> fallback(){
		return Mono.just("fallback");
	}


}
